import 'dart:async';

import 'package:car_music/src/tool/assets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

class LeftDrawer extends StatefulWidget {
  const LeftDrawer({super.key});

  @override
  State<LeftDrawer> createState() => _LeftDrawerState();
}

class _LeftDrawerState extends State<LeftDrawer> {
  final _bleManager = BluetoothManager.instance;
  // 定义 StreamSubscription 来管理订阅
  StreamSubscription<BLEPeripheral>? _scanResultsSubscription;
  List<BLEPeripheral> _deviceList = [];
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
  // late GlobalModelNotifier _global_notify;

  @override
  void initState() {
    super.initState();

    // globalState.addListener(_bluetoothState);
    // 使用 Future 延迟调用避免在 build 期间调用
    Future.delayed(const Duration(seconds: 1), () {
      _refreshIndicatorKey.currentState?.show();
    });
  }

  @override
  void dispose() {
    // globalState.removeListener(_bluetoothState);
    _scanResultsSubscription?.cancel();
    super.dispose();
  }

  // void _bluetoothState(NotifyData newdata) {
  //   if (newdata.key != '蓝牙状态') return;
  //   setState(() {});
  // }

  ///连接外设
  Future<void> _connect(BLEPeripheral peripheral, BuildContext context) async {
    if (_bleManager.connectedDeviceList.any(($0) => $0 == peripheral)) {
      EasyLoading.showInfo('The device will disconnecting');
      _bleManager.disconnect(peripheral);
      return;
    }
    EasyLoading.showInfo('Connecting...');
    await _bleManager.connect(peripheral);
  }

  ///显示的item
  Widget _item(int index, BuildContext context) {
    BLEPeripheral peripheral = _deviceList[index];
    bool conncect = _bleManager.connectedDeviceList.any(($0) => $0 == peripheral);
    return InkWell(
      onTap: () {
        _connect(peripheral, context);
      },
      child: Column(children: [
        ListTile(
          title: Text(_deviceList[index].result.device.advName, style: TextStyle(fontSize: conncect ? 18 : 14)),
          textColor: conncect ? Color_select_btn : Colors.white,
        ),
        SizedBox(
          height: 0.5,
          child: Container(color: Colors.white),
        )
      ]),
    );
  }

  ///刷新扫描
  Future<void> _refresh() async {
    _bleManager.startScan(deviceNameFilter: ['DSP']);

    _scanResultsSubscription = _bleManager.scanResultStream.listen((per) {
      if (mounted) {
        setState(() {
          _deviceList.removeWhere(
              ($0) => $0.result.device.remoteId.str.toUpperCase() == per.result.device.remoteId.str.toUpperCase());
          _deviceList.add(per);
        });
      }
    });
    await Future.delayed(const Duration(seconds: 3));
  }

  ///头视图
  Widget _headView(BuildContext context) {
    return InkWell(
      onTap: () {
        _refreshIndicatorKey.currentState?.show();
      },
      child: Container(
        height: 60,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 20),
        child: const Text('Devices', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white)),
      ),
    );
  }

  ///尾视图
  Widget _bottomView(BuildContext context) {
    Widget title(BuildContext context, String text) {
      return InkWell(
        onTap: () {
          if (text == 'Refresh Device List') {
            _refreshIndicatorKey.currentState?.show();
          } else {
            showAlert(context, 'Are you sure to reset DSP tuning?', ['NO', 'YES'], (value) {
              // ///通知其他页面更新
              // _global_notify.updateProgress();
              // globalModel.upload(tag: 'RESET_DSP', title: 'Resetting...', tips: 'Reset Successfully!');
            });
          }
          print('click ====> ${text}');
        },
        child: Container(
          height: 40,
          alignment: Alignment.center,
          child: Text(text, textAlign: TextAlign.center),
        ),
      );
    }

    return Column(
      children: [
        title(context, 'Refresh Device List'),
        Container(height: 1, color: Colors.white),
        // title(context, 'Reset DSP Tuning')
      ],
    );
  }

  ///list视图
  Widget _listView(BuildContext context) {
    return Expanded(
      child: RefreshIndicator(
          onRefresh: _refresh,
          key: _refreshIndicatorKey,
          child: CustomScrollView(
            slivers: [
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    return _item(index, context);
                  },
                  childCount: _deviceList.length,
                ),
              ),
            ],
          )),
    );
  }

  ///ios下拉刷新风格
  // Widget _listView(BuildContext context) {
  //   return Expanded(
  //     child: CustomScrollView(
  //       slivers: [
  //         CupertinoSliverRefreshControl(
  //           onRefresh: _refresh,
  //         ),
  //         SliverList(
  //             delegate: SliverChildBuilderDelegate((context, index) {
  //           return ListTile(
  //             title: Text('name:${_deviceList[index].device.remoteId}'),
  //             textColor: Colors.white,
  //           );
  //         }, childCount: _deviceList.length)),
  //       ],
  //     ),
  //   );
  // }

  @override
  Widget build(BuildContext context) {
    // _global_notify = Provider.of<GlobalModelNotifier>(context);

    return SafeArea(
      child: Drawer(
        backgroundColor: Colors.transparent,
        child: Stack(
          children: [
            InkWell(
              splashColor: Colors.transparent,
              onTap: () => Navigator.pop(context),
            ),
            Padding(
              padding: const EdgeInsets.only(top: kToolbarHeight),
              child: Container(
                decoration: const BoxDecoration(
                  color: Colors.black, // 背景色
                  borderRadius:
                      BorderRadius.only(topLeft: Radius.circular(20), bottomLeft: Radius.circular(20)), // 设置圆角
                ),
                child: Column(
                  children: [
                    _headView(context),
                    _listView(context),
                    _bottomView(context),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
